<template>
  <div class="wrapper-input-tags">
    <el-tag
      v-for="tag in dynamicTags"
      :key="tag"
      class="tag-box"
      size="large"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      class="tag-ipt"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button
      :icon="Plus"
      v-else
      class="tag-btn"
      @click="showInput"
    ></el-button>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, PropType, ref } from 'vue';
import { ElInput } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const inputValue = ref('');
// const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"]);

// props
const props = defineProps({
  modelValue: {
    type: Array as PropType<Array<string>>,
    default: () => []
  }
});
// emits
const emits = defineEmits(['update:modelValue']);
const dynamicTags = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = '';
};
</script>

<style lang="scss" scoped>
.wrapper-input-tags {
  display: flex;
  flex-wrap: wrap;
  margin-right: -8px;
  margin-bottom: -8px;

  .tag-box {
    margin-right: 8px;
    margin-bottom: 8px;
  }

  .tag-ipt {
    width: 80px;
    height: 32px;
  }

  .tag-btn {
    width: 80px;
  }
}
</style>
